package edu.mse.camel.client.serverlib;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import edu.mse.camel.client.core.events.model.BaselineResourceUpdate;
import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.events.EventIDs;
import edu.mse.camel.client.events.peer.SendGenericPeerEvent;
import edu.mse.camel.client.events.server.JoinSessionEvent;
import edu.mse.camel.client.events.server.LoginEvent;
import edu.mse.camel.client.events.server.LogoutEvent;
import edu.mse.camel.client.events.server.QuerySessionListEvent;
import edu.mse.camel.client.log.Debug;
import edu.mse.camel.client.preference.CamelServerPage;
import edu.mse.camel.client.session.team.QuerySessionParticipantStatus;
import edu.mse.camel.client.session.team.SESSION_CONSTANTS;
import edu.mse.camel.client.session.team.TEAMMEMBER_STATUS;
import edu.mse.camel.client.session.team.TeamList;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin implements IStartup {

	// The plug-in ID
	public static final String PLUGIN_ID = "edu.mse.camel.client.serverlib";

	// The shared instance
	private static Activator plugin;
	
	private ServerLibEventHandler handler;
	
	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;

		Debug.log_info(Activator.PLUGIN_ID, "Server Library has started");
		
		IPreferenceStore store = Activator.getDefault().getPreferenceStore();
        store.setDefault(CamelServerPage.IP, "buzzers.webhop.net");
		
		//getPluginPreferences().setDefault("Camel.Server.JNP", "jnp://buzzers.webhop.net:1099");
		//savePluginPreferences();
		
		handler = new ServerLibEventHandler();
	
		EventManager.getInstance().subscribeTo(EventIDs.LOGIN_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.CREATESESSION_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.QUERY_SESSION_LIST_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.JOINSESSION_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.LEAVE_SESSION_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.LOGOUT_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.QUERY_SESSION_PARTICIPANT_STATUS_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.QUERY_LOGIN_STATUS_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.QUERY_TEAM_STATUS_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.SEND_CHAT_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.SEND_INVITE_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.ASSIGN_ROLE_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.SEND_PEER_EVENT, handler);
		EventManager.getInstance().subscribeTo(EventIDs.SEMAPHORE_EVENT, handler);
		
		//testSessionOperation();

	}
	public static Activator getInstance() {
		return plugin;
	}
	
	private void testSessionOperation () {
		try {
			LoginEvent event = new LoginEvent("mac", "1234");
			EventManager.getInstance().dispatchEventSynchronous(event, true);
			
			if (event.isOpSuccessful()) {
				Debug.log_info(Activator.PLUGIN_ID, "Login successful");
			}
			else {
				Debug.log_warning(Activator.PLUGIN_ID, "Login failed");
			}
			
			JoinSessionEvent event2 = new JoinSessionEvent(84);
			EventManager.getInstance().dispatchEventSynchronous(event2, true);
			if (event2.isOpSuccessful()) {
				Debug.log_info(Activator.PLUGIN_ID, "Join successful");
			}
			else {
				Debug.log_warning(Activator.PLUGIN_ID, "Join failed");
			}
			/*
			QuerySessionParticipantStatus event3 = new QuerySessionParticipantStatus();
			EventManager.getInstance().dispatchEventSynchronous(event3, true);
			if (event3.isOpSuccessful()) {
				Debug.log_info(Activator.PLUGIN_ID, "Query participant status successful");
			}
			else {
				Debug.log_warning(Activator.PLUGIN_ID, "Query participant status failed");
			}
			*/
			/*
			SendGenericPeerEvent peer = new SendGenericPeerEvent();
			BaselineResourceUpdate update = new BaselineResourceUpdate();
			update.setOriginalFileName("test.txt");
			update.setOriginalProjectName("mangobear");
			
			File file = new File("c:\\temp\\test.txt");
			FileInputStream filestream = new FileInputStream(file);
			BufferedInputStream stream = new BufferedInputStream(filestream);
			byte [] bytearray = new byte[100];
			stream.read(bytearray);
			update.setFileBuffer(bytearray);
			peer.setSpecificEventId(EventIDs.BASELINE_RESOURCE_UPDATE_EVENT);
			peer.writeObject(update);
			EventManager.getInstance().dispatchEventAsynchronous(peer);
			
			Debug.log_info(Activator.PLUGIN_ID, "Generic event sent");
			*/

			QuerySessionListEvent eventSessionList = new QuerySessionListEvent();
			EventManager.getInstance().dispatchEventSynchronous(eventSessionList, true);
			if (eventSessionList.isOpSuccessful()) {
				Debug.log_info(Activator.PLUGIN_ID, "Query session list successful");
				for (QuerySessionListEvent.SessionList session : eventSessionList.getSessionList()) {
					Debug.log_info(Activator.PLUGIN_ID, "Session " + session.getsessionId());
					for(String name : session.getParticipants()) {
						Debug.log_info(Activator.PLUGIN_ID, "  name " + name);
					}
				}
			}
			else {
				Debug.log_warning(Activator.PLUGIN_ID, "Query session list failed");
			}

		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		
		// logout if we are still online
		LogoutEvent event = new LogoutEvent();
		EventManager.getInstance().dispatchEventSynchronous(event, false);
		
		plugin = null;
		super.stop(context);
		
		Debug.log_info(Activator.PLUGIN_ID, "Server Library : unsubscribe events");
		
		EventManager.getInstance().unSubscribeTo(EventIDs.LOGIN_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.CREATESESSION_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.QUERY_SESSION_LIST_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.JOINSESSION_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.LEAVE_SESSION_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.LOGOUT_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.QUERY_SESSION_PARTICIPANT_STATUS_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.QUERY_LOGIN_STATUS_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.QUERY_TEAM_STATUS_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.SEND_CHAT_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.SEND_INVITE_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.ASSIGN_ROLE_EVENT, handler);
		EventManager.getInstance().unSubscribeTo(EventIDs.SEND_PEER_EVENT, handler);

		Debug.log_info(Activator.PLUGIN_ID, "Server Library : stopping event handlers");
		handler.stop();
		
		Debug.log_info(Activator.PLUGIN_ID, "Server Library : shutdown completed");
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	@Override
	public void earlyStartup() {
	}

}
